<!-- 线索管理的详情 -->
<template>
  <div class="main">
    <NScrollbar>
      <div class="form_content">
        <div class="content1">
          <NH3>线索详情</NH3>
          <div
            class="content"
            style="display: flex; flex-direction: column; align-items: center"
          >
            <NSpace>
              <DetailFormProvider>
                <NForm
                  disabled
                  ref="formRef"
                  :model="formValue"
                  require-mark-placement="left"
                  label-placement="left"
                  :label-width="115"
                  label-align="right"
                >
                  <NSpace>
                    <NFormItem
                      label="线索名称:"
                      path="clueName"
                    >
                      <NInput
                        v-model:value="formValue.clueName"
                        maxlength="100"
                        placeholder="输入线索名称"
                        style="width: 350px"
                      />
                    </NFormItem>
                    <NFormItem
                      label="线索状态:"
                      path="statusCode"
                    >
                      <NSelect
                        :options="listOption"
                        v-model:value="formValue.statusCode"
                        placeholder="请选择线索状态"
                        clearable
                        style="width: 350px"
                        filterable
                      />
                    </NFormItem>
                  </NSpace>
                  <NSpace>
                    <NFormItem
                      label="藏家"
                      path="collectorId"
                    >
                      <NSelect
                        :options="listNameOption"
                        v-model:value="formValue.collectorId"
                        placeholder="藏家"
                        style="width: 350px"
                        filterable
                      />
                    </NFormItem>
                    <NFormItem
                      label="联系方式:"
                      path="concatUser"
                    >
                      <NInput
                        v-model:value="formValue.concatUser"
                        maxlength="20"
                        placeholder="输入联系人"
                        style="width: 175px"
                      />
                    </NFormItem>
                    <NFormItem
                      label=""
                      path="concatUserPhone"
                      :label-width="10"
                    >
                      <NInput
                        v-model:value="formValue.concatUserPhone"
                        maxlength="20"
                        placeholder="输入联系方式"
                        style="width: 165px"
                      />
                    </NFormItem>
                  </NSpace>
                  <NSpace>
                    <NFormItem
                      label="线索提供时间:"
                      path="provideTime"
                    >
                      <NDatePicker
                        input-readonly
                        v-model:formatted-value="formValue.provideTime"
                        value-fxormat="yyyy-MM-dd HH:mm:ss"
                        type="datetime"
                        default-time="00:00:00"
                        style="width: 350px"
                        placeholder="输入线索提供时间"
                      />
                    </NFormItem>
                    <NFormItem
                      label="线索提供方式:"
                      path="provideType"
                    >
                      <NInput
                        v-model:value="formValue.provideType"
                        maxlength="100"
                        placeholder="输入线索提供方式"
                        style="width: 350px"
                      />
                    </NFormItem>
                  </NSpace>
                  <NFormItem
                    label="征集部对接人:"
                    path="scopeOrPeopleList"
                  >
                    <div style="width: 100%">
                      <!-- <NButton style="width: 115px; margin-bottom: 10rem" type="primary" ghost @click="openScope">
                          选择对接人
                        </NButton> -->
                      <div
                        style="width: 370rem; background-color: #e1e1e1; padding: 10rem 0 8rem"
                        v-if="formValue.scopeOrPeopleList?.length"
                      >
                        <NScrollbar style="max-height: 120rem">
                          <div class="scope">
                            <div
                              class="userBox"
                              v-for="(item, index) in formValue.scopeOrPeopleList"
                              :key="index"
                            >
                              <div>{{ item.typeName }}</div>
                              <n-icon
                                @click="handleScope(item.identifyingId)"
                                style="cursor: pointer"
                              >
                                <CloseFilled />
                              </n-icon>
                            </div>
                          </div>
                        </NScrollbar>
                      </div>
                      <div
                        style="
                          width: 360rem;
                          overflow: hidden;
                          height: 40rem;
                          background-color: #e1e1e1;
                        "
                        v-else
                      ></div>
                    </div>

                    <!-- <NInput v-model:value="formValue.scopeOrPeopleList" maxlength='20' placeholder="输入征集部对接人" style="width: 350px" /> -->
                  </NFormItem>
                  <NFormItem
                    label="版本详情:"
                    path="versionDetails"
                  >
                    <NInput
                      v-model:value="formValue.versionDetails"
                      maxlength="100"
                      type="textarea"
                      placeholder="输入版本详情"
                      style="width: 100%"
                    />
                  </NFormItem>
                  <NFormItem
                    label="线索反馈:"
                    path="feedback"
                  >
                    <NInput
                      v-model:value="formValue.feedback"
                      maxlength="1000"
                      type="textarea"
                      placeholder="输入线索反馈"
                      style="width: 100%"
                    />
                  </NFormItem>
                </NForm>
              </DetailFormProvider>
            </NSpace>
          </div>
        </div>
      </div>
      <div class="form_content">
        <div class="content1">
          <NH3>关联批次</NH3>
          <div
            class="content"
            style="margin-bottom: 120rem; padding-bottom: 20rem"
          >
            <n-data-table
              v-bind="$props"
              :data="tableData"
              :columns="columns"
              :loading="tableLoading"
              bordered
              :max-height="400"
            />
            <div style="margin: 10px 0">
              <NPagination
                show-size-picker
                show-quick-jumper
                :page-sizes="paginationReactive.pageSizes"
                :item-count="paginationReactive.itemCount"
                :page="paginationReactive.page"
                :page-size="paginationReactive.pageSize"
                @update:page="paginationReactive.onChange"
                @update:page-size="paginationReactive.onUpdatePageSize"
              >
                <template #suffix>页</template>
                <template #prefix>
                  <span style="font-size: 14px">共{{ paginationReactive.itemCount }}条</span>
                </template>
              </NPagination>
            </div>
          </div>
        </div>
      </div>
    </NScrollbar>
  </div>
  <!-- 范围选择 -->
  <NModal
    :auto-focus="false"
    v-model:show="modalVisible"
    @close="modalVisible = false"
  >
    <VScope
      @close="modalVisible = false"
      @scopeSubmit="getScopeList"
      :defaultList="scopeList"
      :flat="true"
    />
  </NModal>
  <FixedAction>
    <NSpace justify="center">
      <NButton
        style="width: 78px"
        ghost
        @click="goBack"
      >
        返回
      </NButton>
      <!-- <NButton type="primary" style="width: 78px" @click="confirm" :disabled="loading" :loading="loading">
        保存
      </NButton> -->
    </NSpace>
  </FixedAction>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, reactive, h } from 'vue'
import {
  NSpace,
  NForm,
  NInput,
  NFormItem,
  NButton,
  NScrollbar,
  NSelect,
  useMessage,
  NDatePicker,
  NDataTable,
  NPagination,
  NH3,
  NModal,
  type FormInst,
  NIcon
} from 'naive-ui'
import router from '@/router'
import { useRoute } from 'vue-router'
import FixedAction from '@/components/FixedAction.vue'
import { sendRequest } from '@/utils/api'
import type { HttpResponse } from '@/utils/http'
import { keysOf } from '@/utils/object'
import { format } from 'date-fns'
import { useTagStore } from '@/stores/layout'
import useRouteReplace from '@/hooks/useRouteReplace'

const route = useRoute()
const routeReplace = useRouteReplace(route.query.redirect as string)
const tags = useTagStore().tags
const message = useMessage()
const loading = ref(false)
const formRef = ref<FormInst | null>(null)
const listOption = ref([])
const listNameOption = ref<any>([])
const formValue = reactive({
  clueName: null,
  statusCode: null,
  collectorId: null,
  concatUser: null,
  concatUserPhone: null,
  provideType: null,
  scopeOrPeopleList: [] as any[],
  versionDetails: null,
  feedback: null,
  receiveUser: null,
  provideTime: format(new Date(), 'yyyy-MM-dd HH:mm:ss'),
  regionCode: null,
  regionName: null,
  collectionConcatUser: null
})
const rules = ref({
  clueName: {
    required: true,
    message: '请输入线索名称',
    trigger: ['input', 'blur']
  },
  statusCode: {
    required: true,
    message: '请输入线索状态',
    trigger: ['change', 'blur']
  },
  collectorId: {
    required: true,
    message: '请选择藏家',
    trigger: ['change', 'blur']
  },
  provideType: {
    required: true,
    message: '请输入线索提供方式',
    trigger: ['change', 'blur']
  },
  provideTime: {
    required: true,
    message: '请选择线索提供时间',
    trigger: ['change', 'blur']
  }
})
const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 0,
  onChange: (page: number) => {
    paginationReactive.page = page
    queryTableData()
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    paginationReactive.page = 1
    queryTableData()
  }
})
const columns: any = [
  {
    title: '批次编号',
    key: 'batchCode',
    width: '200rem'
  },
  {
    title: '批次名称',
    key: 'batchName'
  },
  {
    title: '点交状态',
    key: 'pointStatus'
  },

  {
    title: '征集方式',
    key: 'solicitMethod'
  },
  {
    title: '移交人',
    key: 'transferor'
  },
  {
    title: '接收人',
    key: 'receiver'
  },
  {
    title: '接收时间',
    key: 'receiveTime'
  },
  {
    title: '征集数量',
    key: 'solicitNum'
  },
  {
    title: '证书发放',
    key: 'certificateType'
  },
  {
    title: '创建人',
    key: 'creator'
  },
  {
    title: '操作',
    key: 'action',
    align: 'center',
    fixed: 'left',
    render: (e: any) => {
      console.log(e)
      return h(
        NButton,
        {
          color: '#6CB187',
          quaternary: true,
          size: 'small',
          style: {
            // display: e.detail ? 'inline-flex' : 'none'
          },
          onClick: () => {
            router.push({
              name: 'batchDetail',
              params: {
                id: e.batchId
              },
              query: {
                isCreated: String(e.createTime === e.updateTime),
                isEdited: String(e.createTime !== e.updateTime),
                isIdentified: String(e.identifyStatusCode === 'A4104' && e.identifyRegister),
                isRegistered: String(
                  e.click ||
                    (e.identifyStatusCode === 'A4104' && !e.identifyRegister) ||
                    e.pointStatusCode === 'A4202'
                ),
                isNoIdentify: String(e.identifyStatusCode === 'A4102'),
                redirect: router.currentRoute.value.fullPath
              }
            })
          }
        },
        { default: () => '详情' }
      )
    }
  }
]
const tableData = ref([])
const tableLoading = ref(false)
const queryTableData = async (flush = false) => {
  if (flush) paginationReactive.page = 1
  try {
    tableLoading.value = true
    const [error, res] = await sendRequest({
      module: 'clue',
      api: 'querypiciList',
      override: {
        params: {
          limit: paginationReactive.pageSize,
          page: paginationReactive.page,
          id: route.params.id
        }
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    tableData.value = res.data.list
    paginationReactive.itemCount = res.data.totalCount
  } catch (error) {
    console.log(error)
  } finally {
    tableLoading.value = false
  }
}

// 返回
const goBack = () => {
  const index = tags.findIndex((item: any) => item.path === router.currentRoute.value.fullPath)

  tags.splice(index, 1)
  if (tags.length == 0) {
    router.push({ path: '/OA/Workbench/UserDesktop' })
  } else routeReplace()
}
//征集信息-线索下拉
const getFunction = async () => {
  const [error, res] = await sendRequest({
    module: 'collectProcess',
    api: 'listByParentCode',
    override: {
      params: {
        dicCode: 'A62'
      }
    }
  })
  if (error) return message.error(error.message)
  listOption.value = res?.data?.map((it: any) => {
    return { value: it.dicCode, label: it.dicName }
  })
}
const listU = ref<any>([])
//藏家姓名下拉
const getNameFunction = async () => {
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'clue',
    api: 'controllerOptions'
  })
  if (error) return message.error(error.message)
  listNameOption.value = res.data
  listU.value = res.data
}

//新增
const confirm = async () => {
  const validate = await Promise.all([
    new Promise((resolve, reject) => {
      formRef.value?.validate((error) => {
        if (error) return reject(error)
        resolve(true)
      })
    })
  ])
  if (!validate.every(Boolean)) return
  loading.value = true
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'clue',
    api: 'updateNew',
    override: {
      data: {
        ...formValue
      }
    }
  })
  loading.value = false
  if (error) return message.error(error.message)
  message.success(res.msg)
  goBack()
}
// 打开发布范围
const modalVisible = ref(false)
const scopeList = ref()
const openScope = () => {
  scopeList.value = formValue.scopeOrPeopleList
  modalVisible.value = true
}
// 发布范围选择
const getScopeList = (v: any) => {
  formValue.scopeOrPeopleList = v
  modalVisible.value = false
}
// 范围选择是删除
const handleScope = (id: any) => {
  const index = formValue.scopeOrPeopleList?.findIndex((it: any) => it.identifyingId == id)
  formValue.scopeOrPeopleList?.splice(index, 1)
}
const getInfo = async () => {
  await sendRequest<HttpResponse>({
    module: 'clue',
    api: 'infoManage',
    uri: {
      id: route.params.id
    }
  }).then(([err, res]) => {
    if (err) return
    keysOf(formValue).forEach((e) => {
      {
        // @ts-ignore
        formValue[e] = res.data[e] as never
      }
    })
  })
}
onMounted(() => {
  getFunction()
  getNameFunction()
  getInfo()
  queryTableData()
})
</script>

<style scoped lang="scss">
@mixin CommonFont {
  font-size: 16rem;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.85);
}

.main {
  // display: flex;
  // flex-direction: column;
  width: 100%;
  height: 100%;
  overflow: hidden;

  .form_content {
    width: 100%;
    padding: 20rem 20rem 0;
    .content1 {
      width: 100%;
      padding: 10rem 33rem 1rem;
      background-color: #ebeceb;
    }
    .content {
      width: 100%;
      height: 100%;
      padding: 0 33rem 0;
      overflow-y: scroll;
      background-color: #ebeceb;
    }
  }
  .scope {
    display: grid;
    grid-template-columns: repeat(2, auto);
    gap: 10rem 0;
    width: 100%;

    .userBox {
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 170rem;
      height: 40rem;
      margin-left: 7rem;
      background-color: #fff;
      border-radius: 4rem;
      padding: 5px 10rem;
    }
  }
}

.content::-webkit-scrollbar {
  display: none;
}

:deep(.n-spin-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-content) {
  width: 100%;
  height: 100%;
}

:deep(.n-spin-content) {
  width: 100%;
  height: 100%;
}

:deep(.n-base-selection-tags) {
  flex-wrap: nowrap;
  overflow: hidden;
  .n-base-clear {
    display: none;
  }
}
</style>
